<template>
	<div class="clearfix">
		<a-upload
			:action="ACTION"
			:headers="HEADERS"
			accept="image/*"
			multiple
			list-type="picture-card"
			:file-list="fileList"
			:before-upload="beforeUpload"
			@preview="handlePreview"
			@change="handleChange"
			@remove="delImages"
			:disabled="disabled"
		>
			<div v-if="fileList.length < limit && !isShow">
				<plus-outlined />
				<div class="ant-upload-text">上传</div>
			</div>
		</a-upload>
		<a-modal :visible="previewVisible" :footer="null" @cancel="handleCancel">
			<img alt="example" style="width: 100%" :src="previewImage" />
		</a-modal>
	</div>
</template>
<script>
	import tool from '@/utils/tool'
	import sysConfig from '@/config/index'
	function getBase64(file) {
		return new Promise((resolve, reject) => {
			const reader = new FileReader()
			reader.readAsDataURL(file)
			reader.onload = () => resolve(reader.result)
			reader.onerror = (error) => reject(error)
		})
	}
	const headers = ref({
		token: tool.data.get('TOKEN')
	})
	const action = sysConfig.API_URL + '/dev/file/uploadDynamicReturnId'
	export default {
		props: {
			// 上传个数
			limit: {
				type: Number,
				default: 2
			},
			// 文件最大大小 单位mb
			fileSize: {
				type: Number,
				default: 5
			},
			isShow: {
				type: Boolean,
				default: false
			},
			disabled: {
				type: Boolean,
				default: false
			},
			fileIds: {
				type: String,
				default: ''
			}
		},
		data() {
			return {
				loading: false, // 是否有图片正在上传中
				ACTION: action, // 请求地址
				preview: sysConfig.API_URL + '/dev/file/download?id=',
				HEADERS: headers,
				previewVisible: false, // 是否显示预览
				previewImage: '', // 预览图片base64地址
				fileList: [], // 图片列表
				imgIds: []
			}
		},
		watch: {
			fileIds(val) {
				this.initImgs()
			}
		},
		methods: {
			initImgs() {
				if (this.fileIds != null && this.fileIds.length > 0) {
					this.imgIds = this.fileIds.split(',')
					this.fileList = this.fileIds.split(',').map((item) => {
						return {
							status: 'done',
							type: 'image/*',
							url: this.preview + item
						}
					})
				}
			},
			handleCancel() {
				this.previewVisible = false
			},
			async handlePreview(file) {
				if (!file.url && !file.preview) {
					file.preview = await getBase64(file.originFileObj)
				}
				this.previewImage = file.url || file.preview
				this.previewVisible = true
			},
			handleChange(info) {
				const status = info.file.status
				let fileList = info.fileList
				if (status === 'uploading') {
					this.loading = true
				} else if (status === 'done') {
					if (info.file.response.code !== 200) {
						this.$notification.error({
							message: '上传失败',
							description: `${info.file.response.msg}`
						})
					} else {
						this.imgIds.push(info.file.response.data)
						this.$emit('modelValue', this.imgIds.join(','))
					}
					this.loading = false
				} else if (status === 'error') {
					this.$notification.error({
						message: info.file.name + '上传失败',
						description: `status code :${info.file.xhr.status}`
					})
					fileList = fileList.filter((file) => file.uid !== info.file.uid)
				} else if (status === 'beforeUploadReject') {
					if (info.file.statusText) {
						this.$notification.error({
							message: info.file.statusText
						})
					}
				}
				fileList = fileList.filter((file) => file.status !== 'error' && file.status !== 'beforeUploadReject')
				this.fileList = fileList
			},
			beforeUpload(file, fileList) {
				// fileList 只包含了当次上传的文件列表，不包含已上传的文件列表
				// 所以长度要加上已上传的文件列表的长度
				const isLimit = this.fileList.length + fileList.length > this.limit
				const indexOfFile = fileList.findIndex((item) => item.uid === file.uid) + this.fileList.length
				if (isLimit && indexOfFile === this.limit) {
					file.status = 'beforeUploadReject'
					file.statusText = '最多上传' + this.limit + '张图片'
					return false
				}
				if (isLimit && indexOfFile > this.limit) {
					file.status = 'beforeUploadReject'
					return false
				}

				const isJpgOrPng = file.type.startsWith('image/')
				if (!isJpgOrPng) {
					file.status = 'beforeUploadReject'
					file.statusText = '请上传图片'
					return false
				}
				const isLtmb = file.size / 1024 / 1024 < this.fileSize
				if (!isLtmb) {
					file.status = 'beforeUploadReject'
					file.statusText = `图片不能大于${this.fileSize}mb`
					return false
				}
			},
			delImages(i) {
				const da = i.url.split('=')[1]
				this.imgIds.splice(this.imgIds.indexOf(da), 1)
				this.$emit('modelValue', this.imgIds.join(','))
			}
		}
	}
</script>
<style scoped lang="less">
	/* you can make up upload button and sample style by using stylesheets */
	.ant-upload-select-picture-card i {
		font-size: 32px;
		color: #999;
	}

	.ant-upload-select-picture-card .ant-upload-text {
		margin-top: 8px;
		color: #666;
	}
</style>
